import React from 'react';
import ReactDOM from 'react-dom';
import AppBar from '../../components/AppBar';
import { Cart } from './Cart';
import { tajax } from '../../js/tajax';
import { Link } from 'react-router-dom';
import { CItem } from '../../components/CItem';
import { Redirect } from 'react-router-dom'

export class UserShops extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shopList: []
        };
    }

    componentDidMount() {
        tajax({
            url: '/customer/shops',
            method: 'get',
            success: (data) => {
                this.setState({
                    shopList: data.data
                });
            },
            error: (data) => {

            }
        })
    }

    render() {
        let shops = this.state.shopList.map((shop) => {
            let to = "/customer/shop/" + shop.id;
            return <Link to={to} key={shop.id}><div className="card" style={{ marginTop: '10px', padding: '10px' }}>
                <strong>{shop.name}</strong>
                <small>{shop.description}</small>
                <small>起送 ￥{shop.startPrice}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;配送 ￥{shop.shipPrice}</small>
                <small>评分 {shop.rate.toFixed(1)}</small>
            </div></Link>
        })
        return (
            <div>
                <AppBar></AppBar>
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-12">
                            {shops}
                        </div>
                    </div>
                </div>
            </div >
        );
    }
}

export class Shop extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            shop: {
                id: this.props.match.params.id,
                name: '',
                description: '',
                startPrice: 0.0,
                shipPrice: 0.0,
                blocks: [],
                rate: 0.0
            },
            totalPrice: 0.0,
            cart: []
        };
        this.handleAdd = this.handleAdd.bind(this);
        this.handleChooseSpec = this.handleChooseSpec.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleRemove = this.handleRemove.bind(this);
    }

    componentDidMount() {
        tajax({
            url: '/customer/shop/' + this.state.shop.id,
            method: 'get',
            success: (data) => {
                this.setState({
                    shop: data.data
                });
                document.body.setAttribute('data-spy', 'scroll');
                document.body.setAttribute('data-target', '#block-scroll-spy');
                document.body.setAttribute('data-offset', '1');
            }
        });

    }

    handleAdd(item) {
        const cvobj = {
            id: item.id,
            name: item.name,
            image: item.image,
            price: item.price,
            packPrice: item.packPrice,
            spec: item.spec,
            quantity: 1,
            minQuantity: item.minQuantity
        }
        this.setState((prevState, props) => {
            let totalPrice = 0;
            let newCart = [];
            for (var i = 0; i < prevState.cart.length; i++) {
                newCart.push(prevState.cart[i]);
                totalPrice += (prevState.cart[i].price + prevState.cart[i].packPrice) * prevState.cart[i].quantity;
            }
            let hasObj = false;
            for (var i = 0; i < newCart.length; i++) {
                let obj = newCart[i];
                if (obj.id == cvobj.id && obj.spec == cvobj.spec) {
                    // 已存在
                    hasObj = true;
                    newCart[i].quantity += cvobj.quantity;
                    totalPrice += (cvobj.price + cvobj.packPrice) * cvobj.quantity
                    break;
                }
            }

            if (!hasObj) {
                cvobj.quantity = Math.max(item.minQuantity, 1)
                newCart.push(cvobj);
                totalPrice += (cvobj.price + cvobj.packPrice) * cvobj.quantity
            }

            return {
                cart: newCart,
                totalPrice: totalPrice
            };
        })
    }

    handleRemove(item) {
        this.setState((prevState, props) => {
            let totalPrice = 0;
            let newCart = [];
            for (var i = 0; i < prevState.cart.length; i++) {
                let obj = prevState.cart[i];
                if (obj.id == item.id && obj.spec == item.spec) {
                    if (obj.quantity == item.minQuantity) {
                        // 不加入
                    } else {
                        obj.quantity--;
                        totalPrice += (obj.price + obj.packPrice) * obj.quantity;
                        newCart.push(obj);
                    }
                } else {
                    totalPrice += (obj.price + obj.packPrice) * obj.quantity;
                    newCart.push(obj);
                }
            }

            return {
                cart: newCart,
                totalPrice: totalPrice
            };
        })
    }

    handleChooseSpec(spec) {

    }

    handleSubmit() {
        // 下单
        this.props.history.push({
            pathname: '/customer/confirm_order',
            query: {
                cart: this.state.cart,
                shop: this.state.shop
            }
        })
    }

    render() {
        let navLinkActive = false;
        const blocks = this.state.shop.blocks.map((block) => {
            const elm = <li className="nav-item" key={"#" + block.name}>
                <a className={navLinkActive ? 'nav-link' : 'nav-link active'} href={"#" + block.name} style={{ textAlign: 'center' }}>
                    {block.name}
                </a>
            </li>;
            navLinkActive = true;
            return elm;
        });

        const comms = this.state.shop.blocks.map((block) => {
            const cs = block.commodities.map((c) => {
                return (
                    <CItem
                        key={"citem-" + c.id}
                        item={c}
                        handleAdd={this.handleAdd}
                        handleChooseSpec={this.handleChooseSpec}
                    ></CItem>
                );
            });
            return (
                <div id={block.name} key={"block-page-" + block.id} style={{ marginTop: '20px' }}>
                    <small style={{ fontWeight: 'bold' }}>{block.name}</small>
                    {cs}
                </div>
            );
        });

        return (
            <div>
                <AppBar></AppBar>
                <div className="container-fluid" style={{ padding: '20px 10px' }}>
                    <div className="jumbotron">
                        <h1>{this.state.shop.name}</h1>
                        <span>{this.state.shop.description}</span>
                    </div>
                    <div className="row">
                        <nav className="col-2" id="block-scroll-spy">
                            <ul className="nav nav-pills flex-column" style={{}}>
                                {blocks}
                            </ul>
                        </nav>
                        <div className="col-6">
                            {comms}
                        </div>
                        <div className="col-4">
                            <Cart
                                shipPrice={this.state.shop.shipPrice}
                                totalPrice={this.state.totalPrice}
                                handleSubmit={this.handleSubmit}
                                handleRemove={this.handleRemove}
                                handleAdd={this.handleAdd}
                                cart={this.state.cart}
                                startPrice={this.state.shop.startPrice}
                            ></Cart>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}
